package cn.kduck.webapp.websocket;

import cn.kduck.core.web.json.JsonObject;
import cn.kduck.core.web.websocket.DisconnectEventHandler;
import cn.kduck.module.account.service.Account;
import cn.kduck.module.account.service.AccountService;
import cn.kduck.module.user.service.User;
import cn.kduck.module.user.service.UserService;
import cn.kduck.security.principal.AuthUser;
import cn.kduck.security.principal.AuthUserHolder;
import cn.kduck.webapp.security.Kuser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.stereotype.Component;

import java.security.Principal;

@Component
public class DemoDisconnectEventHandler implements DisconnectEventHandler {

    @Autowired
    @Lazy
    private SimpMessagingTemplate template;

    @Autowired
    @Lazy
    private AccountService accountService;

    @Autowired
    @Lazy
    private UserService userService;

    @Override
    public void onDisconnect(Principal principal, String sessionId) {
//        AbstractAuthenticationToken userToken = (AbstractAuthenticationToken)principal;
//        Kuser user = (Kuser)userToken.getPrincipal();
        User user = getUser(principal.getName());
        System.out.println(user.getUserName()+"离开了");

        UserMessage userMessage = new UserMessage();
        userMessage.setMessageType(MessageType.DISCONNECT);
        userMessage.setFromUser(user.getUserName());
        template.convertAndSend("/topic/message",new JsonObject(userMessage));
    }

    private User getUser(String accountName){
        Account account = accountService.getAccountByName(accountName);
        return userService.getUser(account.getUserId());
    }
}
